package com.bicycle.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bicycle.common.entity.base.DataGrid;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.HasViolationEnum;

import com.bicycle.service.dto.BicycleSequenceCloseReportDto;
import com.bicycle.service.dto.BicycleSequenceProcessDto;
import com.bicycle.service.vo.BicycleSequenceDetailProcessVo;
import com.bicycle.service.vo.BicycleSequenceReportDetailVo;
import com.bicycle.service.vo.BicycleSystemUserLoginVo;
import com.bicycle.service.entity.*;


import com.bicycle.service.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "监督执法相关功能")
@Slf4j
@RestController
@RequestMapping("/vehicle")
public class VehicleCaseController extends BaseController {

    @Autowired
    private IBicycleSequenceReportDetailService reportDetailService;
    @Autowired
    private IBicycleSequenceReportProcessService detailProcessRecordService;
    @Autowired
    private IBicycleSequenceReportPhotoService reportPhotoService;
    @Autowired
    private IBicycleSequenceUserService sequenceUserService;
    @Autowired
    private IBicycleCommonFileService commonFileService;
    @Autowired
    private Environment environment;

    /**
     * 智能立案，举报案件-分页查询
     *
     * @param bicycleSequenceReportDetail
     * @return
     * @see
     */
    @ApiOperation("分页查询")
    @RequestMapping(value = "/selectCaseGrid", method = {RequestMethod.POST})
    public DataGrid<BicycleSequenceReportDetail> selectCaseGrid(@RequestBody BicycleSequenceReportDetail bicycleSequenceReportDetail, HttpServletRequest httpServletRequest) {
        DataGrid dataGrid = new DataGrid();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        if (userLoginResp.getRegionId() != null) {
            bicycleSequenceReportDetail.setDistrictId(userLoginResp.getRegionId());
        }
        QueryWrapper<BicycleSequenceReportDetail> queryWrapper = new QueryWrapper<BicycleSequenceReportDetail>(bicycleSequenceReportDetail);
        bicycleSequenceReportDetail.setHasIntelligence(null);
        // 举报类型通过模糊查询
        if (StringUtils.isNotBlank(bicycleSequenceReportDetail.getReportType())) {
            queryWrapper.like("report_type", bicycleSequenceReportDetail.getReportType());
            bicycleSequenceReportDetail.setReportType(null);
        }
        if (StringUtils.isNotBlank(bicycleSequenceReportDetail.getReportNo())) {
            queryWrapper.like("report_no", bicycleSequenceReportDetail.getReportNo());
            bicycleSequenceReportDetail.setReportNo(null);
        }
        if (bicycleSequenceReportDetail.getBeginTime() != null && bicycleSequenceReportDetail.getEndTime() != null) {
            queryWrapper.between("report_time", bicycleSequenceReportDetail.getBeginTime(), bicycleSequenceReportDetail.getEndTime());
        }
        if(environment.getProperty("region.district") != null) {
            queryWrapper.eq("district_id", environment.getProperty("region.district"));
        }
        if(environment.getProperty("region.street") != null) {
            queryWrapper.eq("street_id", environment.getProperty("region.street"));
        }
        //只查询违停和违投案件
        queryWrapper.in("report_type",1,4,5);
        queryWrapper.orderByDesc("report_time");
        queryWrapper.orderByAsc("report_status");
        IPage<BicycleSequenceReportDetail> page = reportDetailService.page(new Page<BicycleSequenceReportDetail>(bicycleSequenceReportDetail.getPage(), bicycleSequenceReportDetail.getRows()), queryWrapper);
        dataGrid.setTotal(page.getTotal());
        dataGrid.setRows(page.getRecords());
        return dataGrid;
    }

    /**
     * 智能立案，举报案件-案件详情
     *
     * @param bicycleSequenceReportDetail
     * @return
     * @see
     */
    @ApiOperation("案件详情")
    @RequestMapping(value = "/selectCaseDetail", method = {RequestMethod.POST})
    public Message<BicycleSequenceReportDetailVo> selectCaseDetail(@RequestBody BicycleSequenceReportDetail bicycleSequenceReportDetail) {
        Message message = new Message();
        BicycleSequenceReportDetailVo reportDetailVo = new BicycleSequenceReportDetailVo();
        bicycleSequenceReportDetail = reportDetailService.getById(bicycleSequenceReportDetail.getDetailId());
        BeanUtil.copyProperties(bicycleSequenceReportDetail, reportDetailVo);

        // 非法车辆编号
        List<String> illegal = new ArrayList<>();
        // 合法车辆编号
        List<String> legal = new ArrayList<>();


        // 智能案件 违规投放 加入非法车辆编号
        if (bicycleSequenceReportDetail != null
                && bicycleSequenceReportDetail.getHasViolation() == HasViolationEnum.HAS_VIOLATION_TRUE.getKey()
                && bicycleSequenceReportDetail.getHasIntelligence() == 1
                && StringUtils.isNotBlank(bicycleSequenceReportDetail.getVehicleNo())) {
            illegal.add(bicycleSequenceReportDetail.getVehicleNo());
        }
        reportDetailVo.setLegal(legal);
        reportDetailVo.setIllegal(illegal);


        // 获取图片地址
        BicycleSequenceReportPhoto qReportDetailPhoto = new BicycleSequenceReportPhoto();
        qReportDetailPhoto.setDetailId(bicycleSequenceReportDetail.getDetailId());
        List<BicycleSequenceReportPhoto> sequenceReportDetailPhotos =
                reportPhotoService.list(new QueryWrapper<BicycleSequenceReportPhoto>(qReportDetailPhoto));

        List<BicycleSequenceReportPhoto> wxReportDetailPhotos = new ArrayList<>();
        List<BicycleSequenceReportPhoto> wxPreDetailPhotos = new ArrayList<>();
        List<BicycleSequenceReportPhoto> wxAfterDetailPhotos = new ArrayList<>();
        sequenceReportDetailPhotos.forEach(sequenceReportDetailPhoto -> {
            if (sequenceReportDetailPhoto.getFileId() != null) {
                BicycleCommonFile bicycleCommonFile =
                        commonFileService.getById(sequenceReportDetailPhoto.getFileId());
                sequenceReportDetailPhoto.setPhotoUrl(bicycleCommonFile.getDownloadPath() + bicycleCommonFile.getRelativePath());
                if (sequenceReportDetailPhoto.getPhotoType() == 1) {
                    // 举报图片
                    wxReportDetailPhotos.add(sequenceReportDetailPhoto);
                } else if (sequenceReportDetailPhoto.getPhotoType() == 2) {
                    // 处理前图片
                    wxPreDetailPhotos.add(sequenceReportDetailPhoto);
                } else if (sequenceReportDetailPhoto.getPhotoType() == 3) {
                    // 处理后图片
                    wxAfterDetailPhotos.add(sequenceReportDetailPhoto);
                }
            }
        });
        if (bicycleSequenceReportDetail.getUserId() != null) {
            BicycleSequenceUser sequenceUserReport = sequenceUserService.getOne(new QueryWrapper<BicycleSequenceUser>(BicycleSequenceUser.builder().userId(bicycleSequenceReportDetail.getUserId()).build()));
            reportDetailVo.setMobile(sequenceUserReport.getMobile());
        }
        reportDetailVo.setReportImages(wxReportDetailPhotos);
        reportDetailVo.setPreImages(wxPreDetailPhotos);
        reportDetailVo.setAfterImages(wxAfterDetailPhotos);


        if (StringUtils.isNotBlank(bicycleSequenceReportDetail.getReportType())) {
            reportDetailVo.setReportType(bicycleSequenceReportDetail.getReportType().split(","));
        } else {
            reportDetailVo.setReportType(new String[0]);
        }
        message.setResult(reportDetailVo);
        return message;
    }

    /**
     * 智能立案，举报案件-案件处理记录
     *
     * @param bicycleSequenceReportProcess
     * @return
     * @see
     */
    @ApiOperation("案件处理记录")
    @RequestMapping(value = "/selectCaseProcess", method = {RequestMethod.POST})
    public Message<List<BicycleSequenceDetailProcessVo>> selectCaseProcess(@RequestBody BicycleSequenceReportProcess bicycleSequenceReportProcess) {
        Message message = new Message();


        List<BicycleSequenceDetailProcessVo> sequenceDetailProcessResps = new ArrayList<>();
        List<BicycleSequenceReportProcess> detailProcessRecords =
                detailProcessRecordService.list(new QueryWrapper<BicycleSequenceReportProcess>(bicycleSequenceReportProcess).orderByAsc("create_time"));
        detailProcessRecords.forEach(detailProcessRecord -> {
            BicycleSequenceDetailProcessVo sequenceDetailProcessResp = new BicycleSequenceDetailProcessVo();
            BeanUtil.copyProperties(detailProcessRecord, sequenceDetailProcessResp);
            List<BicycleSequenceReportPhoto> prePhotos = new ArrayList<>();
            List<BicycleSequenceReportPhoto> afterPhotos = new ArrayList<>();
            // 处理类型才有图片
            if (detailProcessRecord.getOperateType() == 1) {
                // 获取图片地址
                List<BicycleSequenceReportPhoto> reportDetailPhotos =
                        reportPhotoService.list(new QueryWrapper<BicycleSequenceReportPhoto>(BicycleSequenceReportPhoto.builder().processId(detailProcessRecord.getId()).build()));

                reportDetailPhotos.forEach(reportDetailPhoto -> {
                    BicycleCommonFile bicycleCommonFile = commonFileService.getById(reportDetailPhoto.getFileId());
                    reportDetailPhoto.setPhotoUrl(bicycleCommonFile.getDownloadPath() + bicycleCommonFile.getRelativePath());
                    if (reportDetailPhoto.getPhotoType() == 2) {
                        // 处理前图片
                        prePhotos.add(reportDetailPhoto);
                    } else if (reportDetailPhoto.getPhotoType() == 3) {
                        // 处理后图片
                        afterPhotos.add(reportDetailPhoto);
                    }
                });
            }
            sequenceDetailProcessResp.setPrePhotos(prePhotos);
            sequenceDetailProcessResp.setAfterPhotos(afterPhotos);
            sequenceDetailProcessResps.add(sequenceDetailProcessResp);
        });
        message.setResult(sequenceDetailProcessResps);

        return message;
    }

    /**
     * 智能立案，举报案件-案件处理(推送，结案)
     *
     * @param bicycleSequenceProcessDto
     * @return
     * @see
     */
    @ApiOperation("案件处理")
    @RequestMapping(value = "/processCase", method = {RequestMethod.POST})
    public Object processCase(@RequestBody BicycleSequenceProcessDto bicycleSequenceProcessDto, HttpServletRequest httpServletRequest) {
        Message message = new Message();
        BicycleSystemUserLoginVo userLoginResp = this.loginUserInfo(httpServletRequest);
        bicycleSequenceProcessDto.setProcessUserId(userLoginResp.getSysUserId());
        bicycleSequenceProcessDto.setProcessUserName(userLoginResp.getUserName());
        message = reportDetailService.processCase(bicycleSequenceProcessDto);
        return message;
    }

    /**
     * 结案案件操作
     *
     * @param bicycleSequenceCloseReportDto
     * @return
     * @see
     */
    @ApiOperation("结案案件操作")
    @RequestMapping(value = "/closeCase", method = {RequestMethod.POST})
    public Object closeCase(@RequestBody BicycleSequenceCloseReportDto bicycleSequenceCloseReportDto) {
        Message message = new Message();
        message = reportDetailService.closeCase(bicycleSequenceCloseReportDto);
        return message;
    }

}
